import React, { Fragment, useEffect } from "react";
import { useParams, useLocation } from "react-router-dom";
import { Spin } from "antd";
import { FilterArea, ProductList } from "../../components";
import { MainLayout } from "../../layouts/mainLayout";
import { useDispatch } from "react-redux";
import { useSelector } from "../../redux/hooks";
import { searchProduct } from "../../redux/searchSlice/searchSilce";


import styles from "./Search.module.scss";

interface MatchParms {
    keyword: string;
}

export const SearchPage: React.FC = () => {
    const { keyword } = useParams<MatchParms>();
    const loading = useSelector(s => s.searchProduct.loading);
    const error = useSelector(s => s.searchProduct.error);
    const pagination = useSelector(s => s.searchProduct.pagination);
    const productList = useSelector(s => s.searchProduct.data);
    const dispatch = useDispatch();
    const loaction = useLocation();
    useEffect(() => {
        dispatch(searchProduct({ keyword, nextPage: 1, pageSize: 10 }));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [loaction]); // 检测页面url的活动状态，并触发useEffect
    // 切换页数
    const onPageChange = (nextPage: number | string, pageSize: number | string) => {
        dispatch(searchProduct({ keyword, nextPage, pageSize }));
    }

    if (loading) {
        return (
            <Spin size="large" style={{
                marginLeft: "auto",
                marginRight: "auto",
                marginTop: 200,
                marginBottom: 200,
                width: "100%",
            }} />
        )
    }
    if (error) {
        return <div>网站出错，{error}</div>
    }
    if (productList) {
        return (
            <Fragment>
                <MainLayout>
                    <div className={styles['page-content']}>
                        {/* 分类过滤器 */}
                        <div className={styles['product-list-container']}>
                            <FilterArea></FilterArea>
                        </div>
                        {/* 产品列表 */}
                        <div className={styles['product-list-container']}>
                            <ProductList data={productList} paging={pagination} onPageChange={onPageChange}></ProductList>
                        </div>
                    </div>
                </MainLayout>
            </Fragment>
        )
    }
    return <>
        <div>
            数据未返回
        </div>
    </>
}